<?php

namespace App\Console\Commands;

use DOMDocument;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Cloudstudio\Ollama\Facades\Ollama;

class ChangeFetchJobData extends Command
{
    protected $signature   = 'update:jobdata {--examtype=default_examtype} {--city=default_city} {--year=default_year} {--month=default_month} ';
    protected $description = 'Individually update each job data record based on the given criteria';
    /** @var  Client */
    protected $client;

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        ini_set('memory_limit', -1);

        // 获取传入的参数
        $examtype = $this->option('examtype');
        $city = $this->option('city');
        $year = $this->option('year');
        $month = $this->option('month');
        // $field = $this->option('field');
        // $value = $this->option('value');

        // if (!$field || !$value) {
        //     $this->error('Field and value options are required.');
        //     return;
        // }

        // 构建查询
        $query = DB::table('jobs');


        if ($examtype !== 'default_examtype') {
            $query->where('examtype', $examtype);
        }

        if ($city !== 'default_city') {
            $query->where('city', $city);
        }

        if ($year !== 'default_year') {
            $query->whereYear('pubdate', $year);
        }

        if ($month !== 'default_month') {
            $query->whereMonth('pubdate', $month);
        }
        $query->whereNotNull('ht_content');
        $updatedCount = 0;
        // 获取符合条件的数据并逐条更新
        $jobs = $query->get();
        foreach ( $jobs as $job ) {
            try {
                if($job->content){
                    continue;
                }
                if (! $job->ht_content) {
                    continue;
                }
                // 对单条记录进行处理
                $updateData = [];
                // [$htText,$linkUrl]=$this->getLinkUrl($job->url);
                // $updateData['link_url']=$linkUrl;
                // $htText = $this->getGraph($job->ht_content);
                // $htText = $this->getGraph($job->ht_content);
                // $htText = $this->getContent($job->ht_content);

                // if (! $htText) {
                //     continue;
                // }
                // $linkContent=@file_get_contents($linkUrl);
                // if($linkContent){
                //     $updateData['link_content']=$linkContent;
                // }

                // $updateData['graph'] = $htText;
                // $updateData['info'] =strip_tags($htText);
                // 去除多余的换行符，只保留一个换行符
                $updateData['info'] =preg_replace('/\s+/', "\n", $model->info);

                // $updateData['info'] = preg_replace('/\n+/', "\n", $job->info);

                $updateResult = DB::table('jobs')
                                  ->where('id', $job->id)
                                  ->update($updateData);
                if ($updateResult) {
                    $updatedCount++;
                    $this->info("Record with ID {$job->id} has been updated.");
                } else {
                    $this->error("Failed to update record with ID {$job->id}.");
                }
                // sleep(rand(0,2));
            } catch (\Throwable $exception) {
                dd($exception);
                $this->error("Failed to update record with ID {$job->id}.".$exception->getMessage());
                continue;
            }

        }

        $this->info("Total {$updatedCount} record(s) have been updated.");
    }

    public function getLinkUrl($jobUrl)
    {
        $jobUrl = 'https://ha.huatu.com/2024/0828/6012898.html';
        // $jobUrl='https://ha.huatu.com/2024/0102/5550122.html';

        $content = @file_get_contents($jobUrl);
        if ($content === false) {
            return ['', ''];
        }
        // 尝试检测网页内容的字符编码
        $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'ISO-8859-1'], true);

        // 如果检测到的编码不是 UTF-8，则转换为 UTF-8
        if ($encoding && $encoding != 'UTF-8') {
            $utf8_content = mb_convert_encoding($content, 'UTF-8', $encoding);
        } else {
            // 如果已经是 UTF-8 或无法检测到编码，直接使用原始内容
            $utf8_content = $content;
        }
        // 替换全角空格（\u{3000}）为普通空格
        $utf8_content = str_replace("\u{3000}", ' ', $utf8_content);
        // 将文件内容转换为 UTF-8 编码
        $combinedContent = '';
        $url = '';

        // 定义正则表达式模式
        // $pattern = '/<p>\s*文章来源：\s*(https?:\/\/)?(www\.[^\s"]+)\s*<\/p>/i';
        $pattern = '/<p>\s*文章来源：\s*((https?:\/\/)?([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})(\S*)?\s*)<\/p>/i';

        if (preg_match_all($pattern, $utf8_content, $matches)) {

            // $matches[0] 包含完整的匹配项
            // $matches[2] 包含第二个捕获组的内容（即网址部分）
            if (isset($matches[1][0])) {
                $url = trim($matches[1][0]); // 去除两端的空格
                // 检查URL是否以http或https开头，如果没有则追加http://
                if (! preg_match('/^(http|https):\/\//i', $url)) {
                    $url = '//'.$url;
                }
            }
        }

        return [$combinedContent, $url];
    }

    public function getContent($content)
    {
        // $pattern = '/<table[^>]*>.*?<\/table>/si'; // 正则表达式
        // $replacement = ''; // 替换为空
        //
        // $result = preg_replace($pattern, $replacement, $content);
        //
        // return $result;

        $jobUrl = 'https://ha.huatu.com/2024/0102/5550122.html';

        $content = @file_get_contents($jobUrl);
        if ($content === false) {
            return ['', ''];
        }
        // 尝试检测网页内容的字符编码
        $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'ISO-8859-1'], true);

        // 如果检测到的编码不是 UTF-8，则转换为 UTF-8
        if ($encoding && $encoding != 'UTF-8') {
            $utf8_content = mb_convert_encoding($content, 'UTF-8', $encoding);
        } else {
            // 如果已经是 UTF-8 或无法检测到编码，直接使用原始内容
            $utf8_content = $content;
        }
        // 替换全角空格（\u{3000}）为普通空格
        $utf8_content = str_replace("\u{3000}", ' ', $utf8_content);
        // 将文件内容转换为 UTF-8 编码

        $combinedContent = '';
        $url = '';
        $pattern = '/<div class="artBcon">\n*(.*?)\n*<\/div>\n\t\t<!--4\.6新增-->/s';

        preg_match($pattern, $utf8_content, $matches);

        if (preg_match($pattern, $utf8_content, $matches)) {
            $combinedContent = $matches[0];
        }

        return $combinedContent;
        // dd($combinedContent);
    }


    public function getGraph($content)
    {

        // $htmlContent = '...'; // 你的HTML内容
        $graph = '';
        // 正则表达式匹配</table>后面的所有<p>标签内的文本
        preg_match_all('/<table>.*?<\/table>.*?(<p[^>]*>(.*?)<\/p>)/s', $content, $matches);

        // 检查是否有匹配的内容
        if (! empty($matches[1])) {
            // 遍历所有匹配的<p>标签内的文本内容
            foreach ( $matches[1] as $match ) {
                // 提取纯文本内容
                $text = strip_tags($match);
                $graph .= ($text."\n"); // 输出文本内容并换行
            }
        }
        return $graph;



        // 创建一个新的DOMDocument实例
        $dom = new \DOMDocument();

        $dom->encoding = 'UTF-8';

        // 加载HTML内容，使用@符号忽略警告
        @$dom->loadHTML($htmlContent);

        // 获取所有的<p>标签
        $pElements = $dom->getElementsByTagName('p');
        $graph = '';
        // 遍历所有的<p>标签并输出它们的文本内容
        foreach ( $pElements as $p ) {
            $graph .= $p->nodeValue."\n"; // 输出文本内容并换行
        }

        return $graph;
    }

    public function updateAllInfo()
    {

    }
}

